<?php

namespace App\Http\Controllers\Back;

use App\Http\Controllers\Controller;
use App\Model\Partner;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Swagger\Annotations as SWG;

class FinancialController extends Controller
{
    /**
     * @SWG\Get(
     *     path="/back/financial/income",
     *     tags={"后台"},
     *     summary="收益概况",
     *     description="收益概况",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="success",
     *          @SWG\Schema(
     *              @SWG\Property(property="total", type="integer", description="累计收益"),
     *              @SWG\Property(property="vip_total", type="integer", description="累计会员收益"),
     *              @SWG\Property(property="agent_total", type="integer", description="累计代理收益"),
     *              @SWG\Property(property="e_total", type="integer", description="企业佣金"),
     *              @SWG\Property(property="vip_today", type="integer", description="会员当日"),
     *              @SWG\Property(property="agent_today", type="integer", description="代理当日"),
     *              @SWG\Property(property="last_month_total", type="integer", description="上月累计"),
     *              @SWG\Property(property="curr_month_total", type="integer", description="当月累计"),
     *              @SWG\Property(property="new_total", type="integer", description="拉新"),
     *          )
     *      )
     * )
     */
    public function income()
    {
        $userType = Auth::user()->type;
        $data = [];
        switch ($userType) {
            case 1:
                $data = $this->firstIncome();
                break;
            case 2:
                $data = $this->secondIncome();
                break;
            case 3:
                $data = $this->thirdIncome();
                break;
        }
        return $this->renderJson($data);
    }

    /**
     * 管理中心收益概况
     * @return array
     */
    private function firstIncome()
    {
        $p = Partner::where('user_id', Auth::id())->first();
        $data['total'] = DB::table('user_place_partner_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->sum('money');
        $data['vip_total'] = DB::table('user_place_partner_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->where('type', 1)->sum('money');
        $data['agent_total'] = DB::table('operators')->where('place_partner_id', $p->id)->where('examine', 1)->sum('agency_fee')/2;
        $data['e_total'] = DB::table('user_place_partner_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->where('type', 2)->sum('money');
        $data['vip_today'] = DB::table('user_place_partner_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->where('type', 1)->whereRaw('to_days(created_at)=to_days(now())')->sum('money');
        $data['agent_today'] = DB::table('operators')->where('place_partner_id', $p->id)->where('examine', 1)->whereRaw('to_days(examined_at)=to_days(now())')->sum('agency_fee')/2;
        $lastMonthTotal = DB::table('user_place_partner_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->whereRaw("PERIOD_DIFF(date_format(now(), '%Y%m'),date_format(created_at,'%Y%m')) = 1")->sum('money');
        $lastMonthAgent = DB::table('operators')->where('place_partner_id', $p->id)->where('examine', 1)->whereRaw("PERIOD_DIFF(date_format(now(), '%Y%m'),date_format(created_at,'%Y%m')) = 1")->sum('agency_fee');
        $data['last_month_total'] = $lastMonthTotal + ($lastMonthAgent / 2);
        $currMonthTotal = DB::table('user_place_partner_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->whereRaw("DATE_FORMAT(created_at,'%Y%m')=DATE_FORMAT(CURDATE(), '%Y%m')")->sum('money');
        $currMonthAgent = DB::table('operators')->where('place_partner_id', $p->id)->where('examine', 1)->whereRaw("DATE_FORMAT(examined_at,'%Y%m')=DATE_FORMAT(CURDATE(), '%Y%m')")->sum('agency_fee');
        $data['curr_month_total'] = $currMonthTotal + ($currMonthAgent / 2);
        $data['total'] = $data['total'] + $data['agent_total'];
        return $data;
    }

    /**
     * 运营商收益概况
     * @return array
     */
    private function secondIncome()
    {
        $data['total'] = DB::table('user_operators_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->sum('money');
        $data['vip_total'] = DB::table('user_operators_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->where('type', 1)->sum('money');
        $data['e_total'] = DB::table('user_operators_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->where('type', 2)->sum('money');
        $data['vip_today'] = DB::table('user_operators_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->where('type', 1)->whereRaw("to_days(created_at)=to_days(now())")->sum('money');
        $data['last_month_total'] = DB::table('user_operators_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->whereRaw("PERIOD_DIFF(date_format(now(), '%Y%m'),date_format(created_at,'%Y%m')) = 1")->sum('money');
        $data['curr_month_total'] = DB::table('user_operators_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->whereRaw("DATE_FORMAT(created_at,'%Y%m')=DATE_FORMAT(CURDATE(), '%Y%m')")->sum('money');

        return $data;
    }

    private function thirdIncome()
    {
        $data['total'] = DB::table('user_salesman_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->sum('money');
        $data['total'] += DB::table('user_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->sum('money');
        $data['vip_total'] = DB::table('user_salesman_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->where('type', 1)->sum('money');
        $data['vip_total'] += DB::table('user_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->where('type', 1)->sum('money');
        $data['e_total'] = DB::table('user_salesman_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->where('type', 3)->sum('money');
        $data['vip_today'] = DB::table('user_salesman_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->where('type', 1)->whereRaw("to_days(created_at)=to_days(now())")->sum('money');
        $data['last_month_total'] = DB::table('user_salesman_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->whereRaw("PERIOD_DIFF(date_format(now(), '%Y%m'),date_format(created_at,'%Y%m')) = 1")->sum('money');
        $data['last_month_total'] += DB::table('user_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->whereRaw("PERIOD_DIFF(date_format(now(), '%Y%m'),date_format(created_at,'%Y%m')) = 1")->sum('money');
        $data['curr_month_total'] = DB::table('user_salesman_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->whereRaw("DATE_FORMAT(created_at,'%Y%m')=DATE_FORMAT(CURDATE(), '%Y%m')")->sum('money');
        $data['curr_month_total'] += DB::table('user_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->whereRaw("DATE_FORMAT(created_at,'%Y%m')=DATE_FORMAT(CURDATE(), '%Y%m')")->sum('money');
        $data['new_total'] = DB::table('user_salesman_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->where('type', 2)->sum('money');
        $data['new_total'] += DB::table('user_bonus_count')->where('user_id', Auth::id())->where('income_type', 1)->where('type', 2)->sum('money');
        return $data;
    }

    /**
     * @SWG\Get(
     *     path="/back/financial/distribution",
     *     tags={"后台"},
     *     summary="分销提成",
     *     description="分销提成",
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="ok",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="user_name", type="string", description="姓名"),
     *                  @SWG\Property(property="phone", type="string", description="电话"),
     *                  @SWG\Property(property="relation", type="string", description="等级"),
     *                  @SWG\Property(property="pay_time", type="string", description="支付时间"),
     *                  @SWG\Property(property="vip_level", type="string", description="vip等级"),
     *                  @SWG\Property(property="money", type="string", description="金额"),
     *                  @SWG\Property(property="t_money", type="string", description="提成"),
     *                  @SWG\Property(property="t_time", type="string", description="提成时间"),
     *              )
     *          )
     *      )
     * )
     */
    public function distribution()
    {
        return $this->renderJson($this->firstDistribution());
    }

    /**
     * 管理中心分销提成
     * @return array
     */
    private function firstDistribution()
    {
        return DB::table('user_commission_details as ucd')
            ->select('c.user_name', 'u.phone', 'ucd.relation', 'ur.pay_time', 'ur.vip_fee_config_comment as vip_level', 'ur.money', 'ucd.money as t_money', 'ucd.created_at as t_time')
            ->leftJoin('user_recharges as ur', 'ur.out_trade_no', '=', 'ucd.out_trade_no')
            ->leftJoin('users as u', 'u.id', '=', 'ucd.user_id')
            ->leftJoin('cards as c', 'c.user_id', '=', 'ucd.user_id')
            ->where('ucd.relation_id', Auth::id())
            ->when(request('vip'), function ($query, $value) {
                $query->where('ur.vip_fee_config_comment', $value);
            })->when(request('phone'), function ($query, $value) {
                $query->where('u.phone', $value);
            })->when(request('pay_time'), function ($query, $value) {
                $query->where('ur.pay_time', $value);
            })->when(request('t_time'), function ($query, $value) {
                $query->where('ucd.created_at', $value);
            })->paginate(request('limit', 10));
    }

    /**
     * @SWG\Get(
     *     path="/back/financial/agent",
     *     tags={"后台"},
     *     summary="代理提成",
     *     description="代理提成",
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="ok",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="title", type="string", description="名称"),
     *                  @SWG\Property(property="name", type="string", description="负责人"),
     *                  @SWG\Property(property="phone", type="string", description="电话"),
     *                  @SWG\Property(property="gaency_fee", type="string", description="代理费"),
     *                  @SWG\Property(property="examined_at", type="string", description="入驻时间"),
     *                  @SWG\Property(property="money", type="string", description="实际提成"),
     *              )
     *          )
     *      )
     * )
     */
    public function agent()
    {
        if (Auth::user()->type != 1) {
            return $this->fail('身份不符合');
        }
        $id = Partner::where('user_id', Auth::id())->value('id');
        $data = DB::table('operators')
            ->select('title', 'name', 'phone', 'agency_fee', 'examined_at', DB::raw('agency_fee/2 as money'))
            ->where('place_partner_id', $id)
            ->when(request('time'), function ($query, $value) {
                $query->where('created_at', $value);
            })->when(request('phone'), function ($query, $value) {
                $query->where('phone', $value);
            })->paginate(request('limit', 10));
        return $this->renderJson($data);
    }

    /**
     * @SWG\Get(
     *     path="/back/financial/commission",
     *     tags={"后台"},
     *     summary="企业佣金",
     *     description="企业佣金",
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="ok",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="name", type="string", description="公司"),
     *                  @SWG\Property(property="user", type="string", description="用户"),
     *                  @SWG\Property(property="phone", type="string", description="电话"),
     *                  @SWG\Property(property="money", type="string", description="佣金"),
     *                  @SWG\Property(property="r_money", type="string", description="提成"),
     *                  @SWG\Property(property="pay_time", type="string", format="date", description="支付时间"),
     *              )
     *          )
     *      )
     * )
     */
    public function commission()
    {
        $userType = Auth::user()->type;
        $data = [];
        switch ($userType) {
            case 1:
                $data = $this->firstCommission();
                break;
            case 2:
                $data = $this->secondCommission();
                break;
            case 3:
                $data = $this->thirdCommission();
                break;
        }
        return $this->renderJson($data);
    }

    private function firstCommission()
    {
        return DB::table('user_place_partner_bonus_count as upbc')
            ->select('e.name', 'es.name as user', 'es.phone', 'er.money', 'upbc.money as r_money', 'er.pay_time')
            ->leftJoin('enterprise_recharge_fenxiao_queue as eq', 'eq.id', '=', 'upbc.relation_id')
            ->leftJoin('enterprise_recharges as er', 'er.out_trade_no', '=', 'eq.out_trade_no')
            ->leftJoin('enterprise as e', 'e.id', '=', 'er.enterprise_id')
            ->leftJoin('enterprise_staff as es', 'es.id', '=', 'er.staff_id')
            ->where('upbc.user_id', Auth::id())
            ->where('type', 2)
            ->when(request('title'), function ($query, $value) {

            })->when(request('time'), function ($query, $value) {
                $query->where('upbc.created_at', $value);
            })->paginate(request('limit', 10));
    }

    private function secondCommission()
    {
        return DB::table('user_operators_bonus_count as upbc')
            ->select('e.name', 'es.name as user', 'es.phone', 'er.money', 'upbc.money as r_money', 'er.pay_time')
            ->leftJoin('enterprise_recharge_fenxiao_queue as eq', 'eq.id', '=', 'upbc.relation_id')
            ->leftJoin('enterprise_recharges as er', 'er.out_trade_no', '=', 'eq.out_trade_no')
            ->leftJoin('enterprise as e', 'e.id', '=', 'er.enterprise_id')
            ->leftJoin('enterprise_staff as es', 'es.id', '=', 'er.staff_id')
            ->where('upbc.user_id', Auth::id())
            ->where('type', 2)
            ->when(request('title'), function ($query, $value) {

            })->when(request('time'), function ($query, $value) {
                $query->where('upbc.created_at', $value);
            })->paginate(request('limit', 10));
    }

    private function thirdCommission()
    {
        return DB::table('user_salesman_bonus_count as upbc')
            ->select('e.name', 'es.name as user', 'es.phone', 'er.money', 'upbc.money as r_money', 'er.pay_time')
            ->leftJoin('enterprise_recharge_fenxiao_queue as eq', 'eq.id', '=', 'upbc.relation_id')
            ->leftJoin('enterprise_recharges as er', 'er.out_trade_no', '=', 'eq.out_trade_no')
            ->leftJoin('enterprise as e', 'e.id', '=', 'er.enterprise_id')
            ->leftJoin('enterprise_staff as es', 'es.id', '=', 'er.staff_id')
            ->where('upbc.user_id', Auth::id())
            ->where('type', 3)
            ->when(request('title'), function ($query, $value) {

            })->when(request('time'), function ($query, $value) {
                $query->where('upbc.created_at', $value);
            })->paginate(request('limit', 10));
    }

    /**
     * @SWG\Get(
     *     path="/back/financial/lx",
     *     tags={"后台"},
     *     summary="拉新收益",
     *     description="拉新收益",
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="ok",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="name", type="string", description="名字"),
     *                  @SWG\Property(property="phone", type="string", description="电话"),
     *                  @SWG\Property(property="city", type="string", description="城市"),
     *                  @SWG\Property(property="money", type="string", description="收益"),
     *                  @SWG\Property(property="created_at", type="string", format="date", description="时间"),
     *              )
     *          )
     *      )
     * )
     */
    public function lx()
    {
        $data =  DB::table('user_salesman_bonus_count as usbc')
            ->select('c.user_name as name', 'u.phone', 'u.created_at', 'p.name as city', 'usbc.money')
            ->leftJoin('users as u', 'u.id', '=', 'usbc.relation_user_id')
            ->leftJoin('cards as c', 'c.user_id', '=', 'usbc.relation_user_id')
            ->leftJoin('places as p', 'p.id', '=', 'c.city')
            ->where('usbc.user_id', Auth::id())
            ->where('usbc.type', 2)
            ->when(request('phone'), function ($query, $value) {
                $query->where('u.phone', $value);
            })->when(request('time'), function ($query, $value) {
                $query->where('usbc.created_at', $value);
            })->paginate(request('limit', 10));
        return $this->renderJson($data);
    }

    /**
     * @SWG\Get(
     *     path="/back/financial/cash",
     *     tags={"后台"},
     *     summary="结账记录",
     *     description="结账记录",
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="结账记录",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="string", description="id"),
     *                  @SWG\Property(property="type", type="integer", description="type"),
     *                  @SWG\Property(property="bank", type="string", description="银行"),
     *                  @SWG\Property(property="bank_card_no", type="string", description="银行卡号"),
     *                  @SWG\Property(property="bank_card_name", type="string", description="持卡人"),
     *                  @SWG\Property(property="money", type="integer", description="金额"),
     *                  @SWG\Property(property="pay_time", type="string", description="时间"),
     *                  @SWG\Property(property="status", type="integer", description="是否打款0否"),
     *              )
     *          )
     *      )
     * )
     */
    public function cash()
    {

        $m = DB::table('bonus_cash');
        $type = Auth::user()->type;
        switch ($type) {
            case 1:
                $id = DB::table('place_partners')->where('user_id', Auth::id())->value('id');
                $m->where('type', 1)->where('target_id', $id);
                break;
            case 2:
                $id = DB::table('operators')->where('user_id', Auth::id())->value('id');
                $m->where('type', 2)->where('target_id', $id);
                break;
            case 3:
                $id = DB::table('salesmen')->where('user_id', Auth::id())->value('id');
                $m->where('type', 3)->where('target_id', $id);
                break;
        }
        return $this->renderJson($m->paginate(request('limit', 10)));
    }
}
